home *** CD-ROM | disk | FTP | other *** search
/ PC-X 1997 October / pcx14_9710.iso / swag / delphi.swg / 0239_Dynamically calling functions in DLLs.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1997-05-30  |  2.1 KB  |  75 lines

  1.  
  2. --------------------------------------------------------------------------------
  3. By definition DLLs are dynamically loaded libraries of functions and sometimes
  4. data. However, it's possible to either hard code the ability to "import"
  5. functions from DLLs or dynamically "bind" a DLL during the run time --
  6. which of course means that we don't necessarily need to know the name of
  7. the DLL nor the name of the function we're about to call (to a certain extent)
  8. during the time we code. Dynamically loading and unloading DLLs could not
  9. only save memory, but also can help you write programs that are able to
  10. "adjust" itself if certain DLLs are missing.Following "LoadAndRunDLLProcedure()"
  11. function will let you pass the name of the DLL you want to connect to and
  12. the name of the function you want to call. If everything goes well, it will
  13. load the DLL, call the function, and then unload the DLL.
  14.  
  15. function LoadAndRunDLLProcedure(
  16.   sDLL,
  17.   sFunc : string )
  18.   : boolean;
  19. type
  20.   // define the type of "function"
  21.   // we're calling
  22.   TFunc_Start = procedure;
  23. var
  24.   Func_Start : TFunc_Start;
  25.  
  26.   hDll       : THandle;
  27.   FuncPtr    : TFarProc;
  28.   sMsg       : string;
  29. begin
  30.   Result := False;
  31.   hDll   := LoadLibrary(
  32.               PChar( sDLL ) );
  33.   if(hDll > 32)then
  34.   begin
  35.     FuncPtr :=
  36.       GetProcAddress(
  37.         hDll, PChar( sFunc ) );
  38.     @Func_Start := FuncPtr;
  39.     if(nil <> @Func_Start)then
  40.     begin
  41.       Func_Start;
  42.       Result := True;
  43.     end else
  44.     begin
  45.       sMsg := 'DLL entry point ' +
  46.               sFunc + ' not found';
  47.       MessageBox(
  48.         0, PChar( sMsg ), 'Error',
  49.         MB_OK );
  50.     end;
  51.     FreeLibrary( hDll );
  52.   end else
  53.   begin
  54.     sMsg := 'File ' + sDLL +
  55.             ' not found';
  56.     MessageBox(
  57.       0, PChar( sMsg ), 'Error',
  58.       MB_OK );
  59.   end;
  60. end;
  61.  
  62.  
  63. For example, let's say you want to call a procedure called "HelloWorld()"
  64. in a DLL named "MyStuff.DLL:"
  65.  
  66. LoadAndRunDLLProcedure(
  67.   'MyStuff.DLL',
  68.   'HelloWorld' );
  69.  
  70.  
  71. Please note that HelloWorld() must be a procedure, for example, declared as:
  72. procedure HelloWorld;
  73. or in C:
  74. void HelloWorld();
  75.